package consume.raw;

import com.rabbitmq.client.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author : xiaohong
 * @date : 2021/4/14 15:00
 * 手动获取MQ消息
 */

@RestController
@RequestMapping("/get")
public class RawGetConsume {

    // 所有的中间件技术都是基于TCP/IP协议基础上构建的协议规范，只不过rabbitmq遵循的是amqp

    @GetMapping
    public void raw() {
        //创建连接工程
        ConnectionFactory connectionFactory  = new ConnectionFactory();

        connectionFactory.setHost("119.29.67.157");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("xiaohong");
        connectionFactory.setPassword("xiaohong");
        connectionFactory.setVirtualHost("my_vhost");


        Connection connection = null;
        Channel channel = null;
        try {
            //创建连接
            connection = connectionFactory.newConnection("接收者");
            // 通过连接获取通道Channel
            channel = connection.createChannel();
            // 通过通道创建交换机，声明队列，交换关系，路由key，发送消息和接受消息
            // 队列名称
            String queueName = "raw";
            // 手动拉取一条消息
            // 参数2 是否自动ack
            GetResponse response = channel.basicGet(queueName,false);

            if(response != null){
                System.out.println(response.getEnvelope().getDeliveryTag());
                System.out.println(queueName + ":拉取到消息是： " + new String(response.getBody(), "UTF-8"));
                // 手动ack  (这里发现无论是填true还是false都会确认) 所以如果不想ack则可以直接不写
//                channel.basicAck(response.getEnvelope().getDeliveryTag(), false);
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("拉取消息异常");
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {
            // 关闭通道
            if (channel != null && channel.isOpen()){
                try {
                    channel.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            // 关闭连接
            if (connection != null && connection.isOpen()){
                try {
                    connection.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }


    }

}
